package vip.xiaonuo.controller.deviceapi;

import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.jetbrains.annotations.NotNull;
import org.redisson.api.RAtomicLong;
import org.redisson.api.RBucket;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import reactor.core.Reactor;
import reactor.event.Event;
import vip.xiaonuo.controller.deviceapi.dto.TransitDto;
import vip.xiaonuo.controller.deviceapi.param.UploadFeaturePathParam;
import vip.xiaonuo.core.annotion.BusinessLog;
import vip.xiaonuo.core.context.constant.ConstantContextHolder;
import vip.xiaonuo.core.enums.LogAnnotionOpTypeEnum;
import vip.xiaonuo.core.exception.ServiceException;
import vip.xiaonuo.core.pojo.httpclient.ReturnJson;
import vip.xiaonuo.core.pojo.response.ResponseData;
import vip.xiaonuo.core.util.DateUtils;
import vip.xiaonuo.facedoor.modular.device.entity.DeviceCategory;
import vip.xiaonuo.facedoor.modular.devicebase.entity.DeviceBase;
import vip.xiaonuo.facedoor.modular.devicebase.service.DeviceBaseService;
import vip.xiaonuo.facedoor.modular.devicehistory.entity.DeviceHistory;
import vip.xiaonuo.facedoor.modular.devicehistory.service.DeviceHistoryService;
import vip.xiaonuo.facedoor.modular.idcardhistory.entity.IdCardHistory;
import vip.xiaonuo.facedoor.modular.idcardhistory.service.IdCardHistoryService;
import vip.xiaonuo.facedoor.modular.memberfeatures.entity.MemberFeatures;
import vip.xiaonuo.facedoor.modular.memberfeatures.enums.MemberFeaturesTypeEnum;
import vip.xiaonuo.facedoor.modular.memberfeatures.service.MemberFeaturesService;
import vip.xiaonuo.facedoor.modular.memberuser.entity.MemberUser;
import vip.xiaonuo.facedoor.modular.memberuser.service.FacedoorMemberUserService;
import vip.xiaonuo.facedoor.modular.memberuser.service.MemberUserService;
import vip.xiaonuo.facedoor.modular.reactor.dto.MemberAttendanceVo;
import vip.xiaonuo.facedoor.modular.strangehistory.entity.StrangeHistory;
import vip.xiaonuo.facedoor.modular.strangehistory.service.StrangeHistoryService;
import vip.xiaonuo.facedoor.modular.topic.EventTopic;
import vip.xiaonuo.facedoor.modular.visitor.entity.Visitor;
import vip.xiaonuo.facedoor.modular.visitor.service.FacedoorVisitorService;
import vip.xiaonuo.facedoor.modular.visitor.service.VisitorService;
import vip.xiaonuo.facedoor.modular.visitorhistory.entity.VisitorHistory;
import vip.xiaonuo.facedoor.modular.visitorhistory.service.VisitorHistoryService;
import vip.xiaonuo.integrationconfig.model.config.TransLimitConfig;
import vip.xiaonuo.integrationconfig.service.IntegrationService;
import vip.xiaonuo.sys.modular.file.enums.FileTypeEnum;
import vip.xiaonuo.sys.modular.file.service.SysFileInfoService;
import vip.xiaonuo.sys.modular.org.entity.SysOrg;
import vip.xiaonuo.sys.modular.org.service.SysOrgService;

import javax.annotation.Resource;
import java.io.IOException;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.*;
import java.util.concurrent.TimeUnit;

@RestController
@Slf4j
public class DeviceApiController {

    @Autowired
    private FacedoorMemberUserService facedoorMemberUserService;

    @Autowired
    private MemberUserService memberUserService;

    @Autowired
    private DeviceBaseService deviceBaseService;

    @Autowired
    private IdCardHistoryService idCardHistoryService;

    @Resource
    private SysFileInfoService sysFileInfoService;

    @Resource
    private DeviceHistoryService deviceHistoryService;

    @Resource
    private StrangeHistoryService strangeHistoryService;

    @Resource
    private VisitorService visitorService;

    @Resource
    private VisitorHistoryService visitorHistoryService;

    @Resource
    private SysOrgService orgService;

    @Autowired
    private Reactor reactor;

    @Autowired
    private RedissonClient redissonClient;

    @Resource
    private MemberFeaturesService featuresService;

//    @Autowired
//    private IntegrationService integrationService;


    public java.util.Date getDayEnd() {
        Calendar cal = new GregorianCalendar();
        cal.set(Calendar.HOUR_OF_DAY, 23);
        cal.set(Calendar.MINUTE, 59);
        cal.set(Calendar.SECOND, 59);
        return cal.getTime();
    }

    public Date getMouthEnd() {
        Calendar c = Calendar.getInstance();
        c.set(Calendar.DAY_OF_MONTH, c.getActualMaximum(Calendar.DAY_OF_MONTH));
        c.set(Calendar.HOUR_OF_DAY, 23);
        c.set(Calendar.MINUTE, 59);
        c.set(Calendar.SECOND, 59);
        return c.getTime();
    }

    @GetMapping(value = "/deviceApi/v2.0/canTransitByCard")
    @ApiOperation(value = "闸机刷卡通行控制", tags = "闸机刷卡通行控制接口", response = Boolean.class)
    public ResponseData canTransitByCard(@ApiParam("IC卡号") @RequestParam String icCard) throws IOException {
        return ResponseData.success(CollectionUtils.isNotEmpty(memberUserService.list(new LambdaQueryWrapper<MemberUser>().eq(MemberUser::getIcCard, icCard))));
    }

//    @GetMapping(value = "/deviceApi/v2.0/canTransit")
//    @ApiOperation(value = "闸机通行控制", tags = "闸机通行控制接口", response = TransitDto.class)
//    public ResponseData canTransit(@ApiParam("身份证号码") @RequestParam String idCard) throws IOException {
//
////        TransLimitConfig transconfig = integrationService.getConfig("transconfig", TransLimitConfig.class);
//
//        if (!ObjectUtil.equal(transconfig.getLimitOn(), 1)) {
//            throw new ServiceException(500, "未开启统计配置！");
//        }
//        RLock lock = redissonClient.getLock(idCard);
//        TransitDto transitDto = new TransitDto();
//        transitDto.setConfigDayCount(transconfig.getDailyTimes());
//        transitDto.setConfigMouthCount(transconfig.getMonthlyTimes());
//
//        List<MemberUser> list = memberUserService.list(new LambdaQueryWrapper<MemberUser>().eq(MemberUser::getIdCard, idCard).eq(MemberUser::getPersonType, 2));
//        if (CollectionUtils.isNotEmpty(list)) {
//            transitDto.setBlack(Boolean.TRUE);
//            return ResponseData.success(transitDto);
//        } else {
//            transitDto.setBlack(Boolean.FALSE);
//        }
//
//        try {
//            lock.lock();
//            // 获取key
//            String yyyyMMdd = DateUtils.formatDate(new Date(), "yyyyMMdd");
//            String yyyyMM = DateUtils.formatDate(new Date(), "yyyyMM");
//            String dayKey = "D_".concat(idCard).concat("_").concat(yyyyMMdd);
//            String mouthKey = "M_".concat(idCard).concat("_").concat(yyyyMM);
//
//            // 日期
//            RAtomicLong dayR = redissonClient.getAtomicLong(dayKey);
//            if (dayR.isExists()) {
//                long day = dayR.get();
//                transitDto.setDayCount(day);
//                transitDto.setCanTransit(day < transconfig.getDailyTimes());
//            } else {
//                transitDto.setCanTransit(Boolean.TRUE);
//                transitDto.setDayCount(0L);
//            }
//
//            // 月份
//            RAtomicLong mouthR = redissonClient.getAtomicLong(mouthKey);
//            if (mouthR.isExists()) {
//                long mouth = mouthR.get();
//                transitDto.setMouthCount(mouth);
//                if (transitDto.getCanTransit()) {
//                    transitDto.setCanTransit(mouth < transconfig.getMonthlyTimes());
//                }
//            } else {
//                if (transitDto.getCanTransit()) {
//                    transitDto.setCanTransit(Boolean.TRUE);
//                }
//                transitDto.setMouthCount(0L);
//            }
//        } finally {
//            lock.unlock();
//        }
//        return ResponseData.success(transitDto);
//    }

//    public void countTransit(IdCardHistory idCardHistory) {
//
//        RLock lock = redissonClient.getLock(idCardHistory.getIdCard());
//        try {
//            lock.lock();
//
//            // 获取day
//            Date dayEnd = getDayEnd();
//            Date mouthEnd = getMouthEnd();
//
//            // 获取key
//            String yyyyMMdd = DateUtils.formatDate(new Date(), "yyyyMMdd");
//            String yyyyMM = DateUtils.formatDate(new Date(), "yyyyMM");
//            String dayKey = "D_".concat(idCardHistory.getIdCard()).concat("_").concat(yyyyMMdd);
//            String time_Key = "T_".concat(idCardHistory.getIdCard());
//            String mouthKey = "M_".concat(idCardHistory.getIdCard()).concat("_").concat(yyyyMM);
//
//            RBucket<String> time = redissonClient.getBucket(time_Key);
//
//            if (time.isExists()) {
//                log.error("【{}】一分钟只记录刷脸一次", idCardHistory.getIdCard());
//                return;
//            } else {
//                TransLimitConfig transconfig = integrationService.getConfig("transconfig", TransLimitConfig.class);
//                time.set(idCardHistory.getIdCard());
//                time.expire(transconfig.getRepeatInterval(), TimeUnit.SECONDS);
//            }
//
//            // 日期  key新增
//            RAtomicLong day = redissonClient.getAtomicLong(dayKey);
//            if (day.isExists()) {
//                day.incrementAndGet();
//            } else {
//                long expTime = dayEnd.getTime() - new Date().getTime();
//                day.set(1);
//                day.expire(expTime, TimeUnit.MILLISECONDS);
//            }
//
//            RAtomicLong mouth = redissonClient.getAtomicLong(mouthKey);
//            if (mouth.isExists()) {
//                mouth.incrementAndGet();
//            } else {
//                long expTime = mouthEnd.getTime() - new Date().getTime();
//                mouth.set(1);
//                mouth.expire(expTime, TimeUnit.MILLISECONDS);
//            }
//        } catch (IOException e) {
//            throw new RuntimeException(e);
//        } finally {
//            lock.unlock();
//        }
//
//    }

    /**
     * 人脸特征值上传
     *
     * @param uploadFeaturePathParam 上传参数
     * @return 返回结果
     */
    @RequestMapping(value = "/deviceApi/v2.0/uploadFeature")
    @BusinessLog(title = "人脸特征值_上传", opType = LogAnnotionOpTypeEnum.ADD)
    public ReturnJson uploadFeaturePath(UploadFeaturePathParam uploadFeaturePathParam) {
        log.info("特征值上传参数：{}",uploadFeaturePathParam);
        ReturnJson returnJson = new ReturnJson();
        if (StringUtils.isEmpty(uploadFeaturePathParam.getPersonnelId())) {
            returnJson.setCode("0101");
            returnJson.setMsg("参数缺失");
            return returnJson;
        }

        // 访客
        if (StringUtils.isNotBlank(uploadFeaturePathParam.getType()) && ObjectUtil.equal("1", uploadFeaturePathParam.getType())) {
            // todo
            Visitor visitor = visitorService.getById(Long.parseLong(uploadFeaturePathParam.getPersonnelId().substring(1)));
            if (visitor == null) {
                log.info("-----访客人员【{}】不存在，确认传参正确-----", uploadFeaturePathParam.getPersonnelId());
                returnJson.setCode("0201");
                returnJson.setMsg("访客人员不存在，确认传参正确");
                return returnJson;
            }
            visitor.setProperValue(Optional.ofNullable(uploadFeaturePathParam.getFaceFeature()).orElse(""));
            visitor.setFingerVein(Optional.ofNullable(uploadFeaturePathParam.getFingerVeinFeature()).orElse(""));
            visitorService.updateById(visitor);
            log.info("-----访客人员人脸特征上传成功-----");
            // 会员
        } else {
            if (ObjectUtil.equal(uploadFeaturePathParam.getDeviceType(), "locker")) {
                MemberFeatures memberFeatures = new MemberFeatures();
                memberFeatures.setDwMemberUserId(Long.parseLong(uploadFeaturePathParam.getPersonnelId().substring(1)));
                memberFeatures.setType(MemberFeaturesTypeEnum.MEMBER.getValue());
                memberFeatures.setPlatform(DeviceCategory.SUB_TYPE_STORE);
                memberFeatures.setValue(Optional.ofNullable(uploadFeaturePathParam.getFaceFeature()).orElse(""));
                reactor.notify(EventTopic.MEMBER_FACE_VALUE_ADD, Event.wrap(memberFeatures));
            }else if (ObjectUtil.equal(uploadFeaturePathParam.getDeviceType(), "palm")) {
                Long userId = Long.parseLong(uploadFeaturePathParam.getPersonnelId().substring(1));
                MemberFeatures memberFeatures = featuresService.getOne(new LambdaQueryWrapper<MemberFeatures>()
                        .eq(MemberFeatures :: getDwMemberUserId , userId)
                        .eq(MemberFeatures :: getPlatform , DeviceCategory.SUB_TYPE_STORE_PALM));
                if(memberFeatures == null ){
                    memberFeatures = new MemberFeatures();
                    memberFeatures.setDwMemberUserId(userId);
                    memberFeatures.setPlatform(DeviceCategory.SUB_TYPE_STORE_PALM);
                    memberFeatures.setType(MemberFeaturesTypeEnum.MEMBER.getValue());
                }
                memberFeatures.setValue(Optional.ofNullable(uploadFeaturePathParam.getPalmFeature()).orElse(""));
                featuresService.saveOrUpdate(memberFeatures);
                reactor.notify(EventTopic.MEMBER_PALM_VALUE_UPDATE, Event.wrap(memberFeatures));
            } else {
                // 人脸特征值入库
                MemberFeatures memberFeatures = new MemberFeatures();
                memberFeatures.setDwMemberUserId(Long.parseLong(uploadFeaturePathParam.getPersonnelId().substring(1)));
                memberFeatures.setType(MemberFeaturesTypeEnum.MEMBER.getValue());
                memberFeatures.setPlatform(DeviceCategory.SUB_TYPE_FACE);
                memberFeatures.setValue(Optional.ofNullable(uploadFeaturePathParam.getFaceFeature()).orElse(""));
                reactor.notify(EventTopic.MEMBER_FACE_VALUE_ADD, Event.wrap(memberFeatures));
            }
            returnJson.setCode("0000");
            returnJson.setMsg("内部人员人脸特征上传成功");
            log.info("-----内部人员人脸特征上传成功-----");
        }

        returnJson.setMsg("特征值上传成功");
        returnJson.setCode("0000");
        return returnJson;
    }

    @RequestMapping(value = "/deviceApi/v2.0/uploadIdCardRecord", method = RequestMethod.POST)
    public ReturnJson reportData(String deviceId, String name, String sex, String nation, MultipartFile idCardImg,
                                 MultipartFile recordImg, String birth, String address, String id, String temperature,
                                 String result, String score, String time, String healthColor, String stopOverCity,
                                 String hsjc, String hsjcHospital, String hsjcResult, String hsjcTime,
                                 String xcLevel, String openFlag) {
        log.info("开始上传通行记录=====================================【{}】================================================", name);
        ReturnJson rj = new ReturnJson();
        DeviceBase deviceBase = deviceBaseService.getById(Long.parseLong(deviceId));
        if (deviceBase == null) {
            deviceBase = new DeviceBase();
            deviceBase.setId(Long.parseLong(deviceId));
        }
        Date comparedDate = null;
        Date hsjcData = null;
        try {
            DateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            if (StringUtils.isNotBlank(time)) {
                comparedDate = format.parse(time);
            }
            if (StringUtils.isNotBlank(hsjcTime)) {
                if (hsjcTime.contains("T")) {
                    hsjcTime = hsjcTime.replace("T", " ");
                }
                hsjcData = format.parse(hsjcTime);
            }
        } catch (Exception e) {
            rj.setMsg("上传异常，异常信息：" + e.getMessage().replaceAll("\"", ""));
            log.error("上传异常，异常信息：" + e.getMessage().replaceAll("\"", ""));
            e.printStackTrace();
            return rj;
        }

        try {
            // 人证记录保存
            IdCardHistory idCardHistory = new IdCardHistory(deviceBase.getId(), deviceBase.getName(), name, sex, nation, birth, address, id, temperature, result, score, comparedDate, healthColor, stopOverCity, hsjc, hsjcHospital, hsjcResult, hsjcData, xcLevel, openFlag);
            // 核酸检测时间
            idCardHistory.setHsjcTime(hsjcData);

            if (idCardImg != null) {
                String originalFilename = idCardImg.getOriginalFilename();
                if (!ObjectUtil.equal(originalFilename, "NullImage.jpg")) {
                    String idCardImgUrl = sysFileInfoService.uploadFileAndReturnUrl(idCardImg, FileTypeEnum.RECORD);
                    idCardHistory.setIdCardImg(idCardImgUrl);

                }
            }
            if (recordImg != null) {
                String originalFilename = recordImg.getOriginalFilename();
                if (!ObjectUtil.equal(originalFilename, "NullImage.jpg")) {
                    String recordImgUrl = sysFileInfoService.uploadFileAndReturnUrl(recordImg, FileTypeEnum.RECORD);
                    idCardHistory.setImage(recordImgUrl);
                }
            }
            idCardHistory.setStatus("0");

            // 身份证脱敏
            if (StringUtils.isNotBlank(id) && StringUtils.isNotBlank(name)) {

                // 湖山数字哨兵定制
                Boolean hushan_shuzi_shaobing = ConstantContextHolder.getSysConfig("HUSHAN_SHUZI_SHAOBING", Boolean.class, false);
                if (hushan_shuzi_shaobing != null && hushan_shuzi_shaobing) {
                    String idCardBegin4 = id.substring(0, 6);
                    String idCardEnd4 = id.substring(id.length() - 4);
                    List<MemberUser> members = facedoorMemberUserService.findByIdCard(name, idCardBegin4, idCardEnd4);
                    if (!CollectionUtils.isEmpty(members)) {
                        idCardHistory.setJobNum(members.get(0).getJobNum());
                    }
                } else {
                    String idCardBegin4 = id.substring(0, 4);
                    String idCardEnd4 = id.substring(id.length() - 4);
                    List<MemberUser> members = facedoorMemberUserService.findByIdCard(name, idCardBegin4, idCardEnd4);
                    if (!CollectionUtils.isEmpty(members)) {
                        idCardHistory.setJobNum(members.get(0).getJobNum());
                        reactor.notify(new MemberAttendanceVo().setMemberId(members.get(0).getId()).setTime(comparedDate));
                    }
                }
            }
            idCardHistoryService.save(idCardHistory);

//            TransLimitConfig transconfig = integrationService.getConfig("transconfig", TransLimitConfig.class);
//            Integer limitOn = transconfig.getLimitOn();
//            if (ObjectUtil.equal(limitOn, 1) && ObjectUtil.equal(openFlag, "1")) {
//                // 通行记录次数保存
//                countTransit(idCardHistory);
//            }
        } catch (Exception e) {
            rj.setMsg("上传异常，异常信息：" + e.getMessage().replaceAll("\"", ""));
            log.error("上传异常，异常信息：" + e.getMessage().replaceAll("\"", ""));
            e.printStackTrace();
            return rj;
        }
        rj.setCode("0000");
        rj.setMsg("添加成功");
        log.info("0000-上传成功:" + deviceId);
        return rj;
    }

    /**
     * 获取当前系统时间
     */
    @RequestMapping(value = "/deviceApi/v2.0/getCurrentTime")
    public ReturnJson getCurrentTime() {
        ReturnJson rj = new ReturnJson();
        rj.setCode("0000");
        rj.put("timeMills", System.currentTimeMillis());
        return rj;
    }


    /**
     * 上传人脸识别及抓拍图片
     *
     * @param personnelId     人员id
     * @param deviceId        设备编号
     * @param faceImage       抓拍图片
     * @param healthCodeImg   健康码
     * @param healthCodeColor 健康码颜色
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/deviceApi/v2.0/reportData", method = RequestMethod.POST)
    public ReturnJson reportData(String personnelId,
                                 String deviceId,
                                 String time,
                                 String verifyType,
                                 @RequestParam(required = false) MultipartFile faceImage,
                                 @RequestParam(required = false) MultipartFile faceImage2,
                                 String icNum,
                                 String erCode,
                                 String temperature,
                                 @RequestParam(required = false) MultipartFile healthCodeImg,
                                 @RequestParam(required = false) String healthCodeColor,
                                 // 存储柜新增
                                 String cabinetNo,
                                 String putTime,
                                 String takeTime,
                                 String takeType) {
        log.info("===========reportData===========");

        ReturnJson rj = new ReturnJson();
        try {
            DeviceBase deviceBase = deviceBaseService.getById(deviceId);
            if (null == deviceBase) { // 设备不存在，防止这里我回复“0202”设备不处理一直循环上传该条数据导致历史记录无法上传问题，这里直接回复设备上传成功
                rj.setCode("0000");
                rj.setMsg("上传成功");
                log.info("0000-无此设备:" + deviceId);
                return rj;
            }
            // 存储柜
            if (ObjectUtil.equal(deviceBase.getDeviceType(), "5")) {
                return LockerRecord(personnelId, deviceId, faceImage, faceImage2, cabinetNo, putTime, takeTime, takeType, rj, deviceBase);
            }

            // 是否是考勤机
            boolean isAttendanceMachine = ObjectUtil.equal(deviceBase.getIsAttendanceMachine(), Boolean.TRUE);

            DateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            Date date1 = format.parse(time);
            if (verifyType.equals("1") || verifyType.equals("4") || verifyType.equals("7") || verifyType.equals("10") // 内部员工外来访客人脸记录、刷卡记录、二维码记录、指静脉
                    || verifyType.equals("11")
                    || verifyType.equals("13")
                    || verifyType.equals("14")
                    || verifyType.equals("15")
            ) {
                log.info("----内部员工通行记录上传----");
                if (StringUtils.isEmpty(personnelId)) {
                    rj.setCode("0101");
                    rj.setMsg("personnelId参数有误");
                    log.info("0101-personnelId参数有误:" + deviceId);
                    return rj;
                }
                // 更新体温信息
                MemberUser member = memberUserService.getById(personnelId.substring(1));
                DeviceHistory deviceHistory = new DeviceHistory();

                // 对30秒内重复上传的数据进行筛选，如果30秒内温度有高温-低温之间的变化时则记录，@mod by tangjian 2020.03.23
                if (member != null) {
                    deviceHistory.setTemperature(temperature);
                    deviceHistory.setDeviceBaseId(deviceBase.getId());
                    deviceHistory.setDeviceName(deviceBase.getName());
                    deviceHistory.setMemberId(member.getId());
                    deviceHistory.setOrgId(member.getOrgId());
                    deviceHistory.setMemberName(member.getName());
                    deviceHistory.setMemberJobNum(member.getJobNum());
                    deviceHistory.setDeviceCurrentDate(date1);
                    // 如果是指静脉人脸一体机，则把记录类型改成指静脉人脸一体机记录 @mod by tangjian 2020.05.15
                    if (deviceBase.getDeviceType().equals("4")) {
                        deviceHistory.setType(4);
                    } else if (deviceBase.getDeviceType().equals("5")) {
                        // 人脸门禁机，这里和人脸测温区分
                        deviceHistory.setType(2);
                    } else if (deviceBase.getDeviceType().equals("1")) {
                        // 人脸测温门禁
                        deviceHistory.setType(1);
                    }
                    // 内部人员通行
                    if (verifyType.equals("1")
                            || verifyType.equals("11")
                            || verifyType.equals("13")
                            || verifyType.equals("14")
                            || verifyType.equals("15")) {
                        deviceHistory.setVerifyType(Integer.parseInt(verifyType));
                        deviceHistory.setIcNum(icNum);
                        deviceHistory.setErCode(erCode);

                        if (faceImage == null && verifyType.equals("1")) {
                            rj.setCode("0105");
                            rj.setMsg("上传内部人员记录时未上传图片");
                            log.info("0105-上传内部人员记录时未上传图片:" + deviceId);
                            return rj;
                        }

                        if (faceImage != null) {
                            deviceHistory.setImage(sysFileInfoService.uploadFileAndReturnUrl(faceImage, FileTypeEnum.RECORD));

                            if (healthCodeImg != null) {
                                deviceHistory.setImage(sysFileInfoService.uploadFileAndReturnUrl(healthCodeImg, FileTypeEnum.RECORD));
                                deviceHistory.setHealthColor(healthCodeColor);
                            } else {
                                log.info("0105-上传内部人员记录时未上传健康码:" + deviceId);
                            }
                        }
                        deviceHistoryService.save(deviceHistory);
                        // 发布签到事件
                        if(isAttendanceMachine){
                            reactor.notify(EventTopic.MEMBER_ATTENDANCE, Event.wrap(new MemberAttendanceVo().setMemberId(member.getId()).setTime(date1)));
                        }

                    } else if (verifyType.equals("4")) { // 刷卡访问
                        if (StringUtils.isEmpty(icNum)) {
                            rj.setCode("0103");
                            rj.setMsg("icNum参数缺失");
                            log.info("0103-icNum参数缺失:" + deviceId);
                            return rj;
                        }
                        deviceHistory.setVerifyType(2);
                        deviceHistory.setIcNum(icNum);
                        if (healthCodeImg != null) {
                            deviceHistory.setHealthCode(sysFileInfoService.uploadFileAndReturnUrl(healthCodeImg, FileTypeEnum.RECORD));
                            deviceHistory.setHealthColor(healthCodeColor);
                        }
                        deviceHistoryService.save(deviceHistory);
                        // 发布签到事件
                        if(isAttendanceMachine){
                            reactor.notify(EventTopic.MEMBER_ATTENDANCE, Event.wrap(new MemberAttendanceVo().setMemberId(member.getId()).setTime(date1)));
                        }
                    } else if (verifyType.equals("7")) {
                        if (StringUtils.isEmpty(erCode)) {
                            rj.setCode("0104");
                            rj.setMsg("erCode参数缺失");
                            log.info("0104-erCode参数缺失:" + deviceId);
                            return rj;
                        }
                        deviceHistory.setVerifyType(3);
                        deviceHistory.setErCode(erCode);
                        if (healthCodeImg != null) {
                            deviceHistory.setHealthCode(sysFileInfoService.uploadFileAndReturnUrl(healthCodeImg, FileTypeEnum.RECORD));
                            deviceHistory.setHealthColor(healthCodeColor);
                        }
                        deviceHistoryService.save(deviceHistory);
                        // 发布签到事件
                        if(isAttendanceMachine){
                            reactor.notify(EventTopic.MEMBER_ATTENDANCE, Event.wrap(new MemberAttendanceVo().setMemberId(member.getId()).setTime(date1)));
                        }
                    } else { // 指静脉
                        deviceHistory.setVerifyType(4);
                        if (healthCodeImg != null) {
                            deviceHistory.setHealthCode(sysFileInfoService.uploadFileAndReturnUrl(healthCodeImg, FileTypeEnum.RECORD));
                            deviceHistory.setHealthColor(healthCodeColor);
                        }
                        deviceHistoryService.save(deviceHistory);
                    }
                    rj.setCode("0000");
                    rj.setMsg("上传成功");
                    log.info("0000-上传成功:" + deviceId);

                    // 发布签到事件
                    if(isAttendanceMachine){
                        reactor.notify(EventTopic.MEMBER_ATTENDANCE, Event.wrap(new MemberAttendanceVo().setMemberId(member.getId()).setTime(date1)));
                    }

                } else {
                    rj.setCode("0000");
                    rj.setMsg("上传成功");
                    log.info("0201-无此人员:" + personnelId);
                    return rj;
                }
            } else if (verifyType.equals("3") || verifyType.equals("6") || verifyType.equals("9")) {
                log.info("-----陌生人脸记录上传-----");
                StrangeHistory strangeHistory = new StrangeHistory();
                strangeHistory.setDeviceCurrentDate(date1);
                strangeHistory.setDeviceBaseId(deviceBase.getId());
                strangeHistory.setDeviceName(deviceBase.getName());
                strangeHistory.setTemperature(temperature); // 体温
                if (deviceBase.getDeviceType().equals("4")) {
                    // 指静脉一体机记录
                    strangeHistory.setType(4);
                } else if (deviceBase.getDeviceType().equals("5")) {
                    // 人脸门禁记录，这里和人脸测温区分
                    strangeHistory.setType(2);
                } else if (deviceBase.getDeviceType().equals("1")) {
                    // 人脸测温门禁记录
                    strangeHistory.setType(1);
                }
                if (verifyType.equals("3")) { // 陌生人脸记录
                    if (faceImage != null) {
                        strangeHistory.setVerifyType(1);
                        strangeHistory.setImage(sysFileInfoService.uploadFileAndReturnUrl(faceImage, FileTypeEnum.RECORD));
                        if (healthCodeImg != null) {
                            strangeHistory.setHealthCode(sysFileInfoService.uploadFileAndReturnUrl(healthCodeImg, FileTypeEnum.RECORD));
                            strangeHistory.setHealthColor(healthCodeColor);
                        }
                        strangeHistoryService.save(strangeHistory);

                    } else {
                        rj.setCode("0105");
                        rj.setMsg("上传陌生人脸记录时未上传图片");
                        log.info("0105-上传陌生人脸记录时未上传图片:" + deviceId);
                        return rj;
                    }
                } else if (verifyType.equals("6")) {
                    if (StringUtils.isEmpty("icNum")) {
                        rj.setCode("0103");
                        rj.setMsg("icNum参数缺失");
                        log.info("0103-icNum参数缺失:" + deviceId);
                        return rj;
                    }
                    strangeHistory.setIcNum(icNum);
                    strangeHistory.setVerifyType(2);
                    if (healthCodeImg != null) {
                        strangeHistory.setHealthCode(sysFileInfoService.uploadFileAndReturnUrl(healthCodeImg, FileTypeEnum.RECORD));
                        strangeHistory.setHealthColor(healthCodeColor);
                    }
                    strangeHistoryService.save(strangeHistory);
                } else if (verifyType.equals("9")) {
                    if (StringUtils.isEmpty("erCode")) {
                        rj.setCode("0104");
                        rj.setMsg("erCode参数缺失");
                        log.info("0104-erCode参数缺失:" + deviceId);
                        return rj;
                    }
                    strangeHistory.setErCode(erCode);
                    strangeHistory.setVerifyType(3);
                    if (healthCodeImg != null) {
                        strangeHistory.setHealthCode(sysFileInfoService.uploadFileAndReturnUrl(healthCodeImg, FileTypeEnum.RECORD));
                        strangeHistory.setHealthColor(healthCodeColor);
                    }
                    strangeHistoryService.save(strangeHistory);
                }
                rj.setCode("0000");
                rj.setMsg("上传成功");
                log.info("0000-上传成功:" + deviceId);
                // 访客
            } else if (verifyType.equals("2") || verifyType.equals("5") || verifyType.equals("8") || verifyType.equals("12")) {
                log.info("-------访客刷脸通行记录上传-----");
                if (StringUtils.isEmpty(personnelId)) {
                    rj.setCode("0000");
                    rj.setMsg("personnelId参数有误");
                    log.info("verifyType:" + verifyType);
                    log.info("0101-访客personnelId参数有误:" + deviceId);
                    return rj;
                }
                // 记录访客的体温
                Visitor visitor = visitorService.getById(Long.parseLong(personnelId.substring(1)));
                if (null == visitor) {
                    rj.setCode("0000");
                    rj.setMsg("上传成功");
                    log.info("这里是访客记录上传，实际根据id查询不到访客，但是直接返回成功，过滤这条数据:" + personnelId);
                    return rj;
                }
                visitor.setTemperature(temperature);
                visitorService.updateById(visitor);
                //                    DeviceBase deviceBase = deviceBaseService.get(deviceId);
                VisitorHistory visitorHistory = new VisitorHistory();
                visitorHistory.setVerifyType(verifyType);
                visitorHistory.setDeviceName(deviceBase.getName());
                visitorHistory.setDeviceBaseId(deviceBase.getId());
                visitorHistory.setVisitorId(visitor.getId());
                visitorHistory.setDeviceCurrentDate(date1);
                visitorHistory.setVisitorName(visitor.getName());
                visitorHistory.setErCode(erCode);
                visitorHistory.setTemperature(temperature);
                visitorHistory.setIcNum(icNum);
                if (ObjectUtil.isNotEmpty(visitor.getOrgId())) {
                    visitorHistory.setOrgId(visitor.getOrgId());
                    SysOrg sysOrg = orgService.getById(visitor.getOrgId());
                    if (sysOrg != null) {
                        visitorHistory.setOrgName(sysOrg.getName());
                    }
                }
                // 根据机器类型增加对应的记录类型 @mod by tangjian 2020.06.02
                if (deviceBase.getDeviceType().equals("4")) {
                    // 指静脉一体机记录
                    visitorHistory.setType(4);
                } else if (deviceBase.getDeviceType().equals("5")) {
                    // 人脸门禁记录，这里和人脸测温区分
                    visitorHistory.setType(2);
                } else if (deviceBase.getDeviceType().equals("1")) {
                    // 人脸测温门禁记录
                    visitorHistory.setType(1);
                }
                if (verifyType.equals("2")) {
                    // 访客人脸
                    if (faceImage != null) {
                        visitorHistory.setVerifyType("1");
                        visitorHistory.setImage(sysFileInfoService.uploadFileAndReturnUrl(faceImage, FileTypeEnum.RECORD));
                        if (healthCodeImg != null) {
                            visitorHistory.setHealthCode(sysFileInfoService.uploadFileAndReturnUrl(healthCodeImg, FileTypeEnum.RECORD));
                            visitorHistory.setHealthColor(healthCodeColor);
                        }
                        visitorHistoryService.save(visitorHistory);
                    } else {
                        rj.setCode("0105");
                        rj.setMsg("上传访客人员记录时未上传图片");
                        log.info("0105-上传访客人员记录时未上传图片:" + deviceId);
                        return rj;
                    }
                } else if (verifyType.equals("5")) { // 刷卡
                    if (StringUtils.isEmpty(icNum)) {
                        rj.setCode("0103");
                        rj.setMsg("icNum参数缺失");
                        log.info("0103-icNum参数缺失:" + deviceId);
                        return rj;
                    }
                    visitorHistory.setVerifyType("2");
                    visitorHistory.setIcNum(icNum);
                    if (healthCodeImg != null) {
                        visitorHistory.setHealthCode(sysFileInfoService.uploadFileAndReturnUrl(healthCodeImg, FileTypeEnum.RECORD));
                        visitorHistory.setHealthColor(healthCodeColor);
                    }
                    visitorHistoryService.save(visitorHistory);
                } else if (verifyType.equals("8")) {
                    if (StringUtils.isEmpty("erCode")) {
                        rj.setCode("0104");
                        rj.setMsg("erCode参数缺失");
                        log.info("0104-erCode参数缺失:" + deviceId);
                        return rj;
                    }
                    visitorHistory.setErCode(erCode);
                    visitorHistory.setVerifyType("3");
                    if (healthCodeImg != null) {
                        visitorHistory.setHealthCode(sysFileInfoService.uploadFileAndReturnUrl(healthCodeImg, FileTypeEnum.RECORD));
                        visitorHistory.setHealthColor(healthCodeColor);
                    }
                    visitorHistoryService.save(visitorHistory);
                } else {
                    if (faceImage != null) {
                        visitorHistory.setVerifyType("12");
                        visitorHistory.setImage(sysFileInfoService.uploadFileAndReturnUrl(faceImage, FileTypeEnum.RECORD));
                        visitorHistoryService.save(visitorHistory);
                    }
                    visitorHistory.setIcNum(icNum);
                    visitorHistory.setErCode(erCode);
                    visitorHistoryService.save(visitorHistory);
                }
                rj.setCode("0000");
                rj.setMsg("上传成功");
                log.info("0000-上传成功:" + deviceId);
            } else {
                //                    rj.setCode("0000");
                //                    rj.setMsg("上传成功");
                rj.setCode("0106");
                rj.setMsg("verifyType参数有误");
                log.info("0106-verifyType参数有误:" + deviceId);
                return rj;
            }
        } catch (Exception e) {
            if ("org.apache.catalina.connector.ClientAbortException".equals(e.getClass().getName())) {
                log.error("发生clientAbortException");
                return null;
            }
            rj.setMsg("上传异常，异常信息：" + e.getMessage().replaceAll("\"", ""));
            log.error("上传异常，异常信息：" + e.getMessage().replaceAll("\"", ""));
            e.printStackTrace();
        }
        return rj;
    }

    @NotNull
    private synchronized ReturnJson LockerRecord(String personnelId, String deviceId, MultipartFile faceImage, MultipartFile faceImage2, String cabinetNo,
                                                 String putTime, String takeTime, String takeType, ReturnJson rj, DeviceBase deviceBase) throws ParseException {
        DateFormat forMats2 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        DateFormat forMats = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        if (StringUtils.isEmpty(putTime)) {
            rj.setCode("0101");
            rj.setMsg("putTime参数未传递");
            log.info("0101-putTime参数未传递:" + deviceId);
            return rj;
        }
        List<DeviceHistory> deviceHistorys = deviceHistoryService
                .list(new LambdaQueryWrapper<DeviceHistory>().eq(DeviceHistory::getPutTime, forMats2.parse(putTime)).eq(DeviceHistory::getCabinetNo, cabinetNo));
        if (CollectionUtils.isNotEmpty(deviceHistorys)) {
            DeviceHistory deviceHistory = deviceHistorys.get(0);
            deviceHistory.setDeviceBaseId(deviceBase.getId());
            deviceHistory.setDeviceName(deviceBase.getName());
            deviceHistory.setTakeType(takeType);
            deviceHistory.setCabinetNo(cabinetNo);
            if (faceImage != null) {
                deviceHistory.setImage(sysFileInfoService.uploadFileAndReturnUrl(faceImage, FileTypeEnum.RECORD));
            }
            if (faceImage2 != null) {
                deviceHistory.setImage2(sysFileInfoService.uploadFileAndReturnUrl(faceImage2, FileTypeEnum.RECORD));
            }
            if(faceImage == null && faceImage2 == null){
                deviceHistory.setType(4);
            }
            if (StringUtils.isNotBlank(takeTime)) {
                deviceHistory.setTakeTime(forMats.parse(takeTime));
            }
            if (StringUtils.isNotBlank(putTime)) {
                deviceHistory.setPutTime(forMats2.parse(putTime));
            }
            // 管理员开锁
            if (ObjectUtil.equal(takeType, "1")) {
                if (StringUtils.isEmpty(personnelId)) {
                    rj.setCode("0101");
                    rj.setMsg("personnelId参数有误");
                    log.info("0101-personnelId参数有误:" + deviceId);
                    return rj;
                }
                MemberUser member = memberUserService.getById(personnelId.substring(1));
                if (member != null) {
                    deviceHistory.setMemberId(member.getId());
                    deviceHistory.setOrgId(member.getOrgId());
                    deviceHistory.setMemberName(member.getName());
                    deviceHistory.setMemberJobNum(member.getJobNum());
                }
            }
            deviceHistoryService.updateById(deviceHistory);
            rj.setCode("0000");
            rj.setMsg("上传成功");
            return rj;
        }
        DeviceHistory deviceHistory = new DeviceHistory();
        deviceHistory.setDeviceBaseId(deviceBase.getId());
        deviceHistory.setDeviceName(deviceBase.getName());
        deviceHistory.setTakeType(takeType);
        deviceHistory.setCabinetNo(cabinetNo);
        if (StringUtils.isNotBlank(takeTime)) {
            deviceHistory.setTakeTime(forMats.parse(takeTime));
        }
        if (StringUtils.isNotBlank(putTime)) {
            deviceHistory.setPutTime(forMats2.parse(putTime));
        }
        if (faceImage != null) {
            deviceHistory.setImage(sysFileInfoService.uploadFileAndReturnUrl(faceImage, FileTypeEnum.RECORD));
        }
        if (faceImage2 != null) {
            deviceHistory.setImage2(sysFileInfoService.uploadFileAndReturnUrl(faceImage2, FileTypeEnum.RECORD));
        }
        // 管理员开锁
        if (ObjectUtil.equal(takeType, "1")) {
            if (StringUtils.isEmpty(personnelId)) {
                rj.setCode("0101");
                rj.setMsg("personnelId参数有误");
                log.info("0101-personnelId参数有误:" + deviceId);
                return rj;
            }
            MemberUser member = memberUserService.getById(personnelId.substring(1));
            if (member != null) {
                deviceHistory.setMemberId(member.getId());
                deviceHistory.setOrgId(member.getOrgId());
                deviceHistory.setMemberName(member.getName());
                deviceHistory.setMemberJobNum(member.getJobNum());
            }
        }
        deviceHistoryService.save(deviceHistory);
        rj.setCode("0000");
        rj.setMsg("上传成功");
        return rj;
    }
}
